<template>

    <HeaderSearch></HeaderSearch>
    <headerMenu :is-search-product="true"></headerMenu>

    <div class="content mar_20">
    	<img src="/images/img1.jpg" />        
    </div>
    <!--Begin 第一步：查看购物车 Begin -->
    <div class="content mar_20">
    	<table border="0" class="car_tab" style="width:1200px; margin-bottom:50px;" cellspacing="0" cellpadding="0">
            <thead>
                <tr>
                    <td class="car_th" width="490">商品名称</td>
                    <td class="car_th" width="150">购买数量</td>
                    <td class="car_th" width="130">小计</td>
                    <td class="car_th" width="150">操作</td>
                </tr>
            </thead>
            <tbody >
                <!-- class="car_tr" -->
                <tr v-for="(product,index) in productList">
                    <td>
                        <div class="c_s_img"><img :src="url + product.fileName" width="73" height="73" /></div>
                        {{ product.name }}
                    </td>
                    <td align="center">
                        <div class="c_num">
                            <input type="button" value="" @click.prevent="updateProductCount(product.id, product.stock,product.quantity-1)" class="car_btn_1" />
                            <input type="text" v-model="product.quantity" name="quantity"  @change="updateQuantity(product.quantity,index,product.id)" class="car_ipt" />  
                            <input type="button" value="" @click.prevent="updateProductCount(product.id, product.stock,product.quantity+1)" class="car_btn_2" />
                        </div>
                    </td>
                    <td align="center" style="color:#ff4e00;">￥{{ product.price * product.quantity }}</td>
                    <td align="center"><a  @click.prevent="updateProductCount(product.id, product.stock,0)">删除</a>&nbsp; &nbsp;<a @click="addLike(product.id)">加入收藏</a></td>
                </tr>

                <tr height="70">
                    <td colspan="6" style="font-family:'Microsoft YaHei'; border-bottom:0;">
                        <label class="r_txt"><button @click="cleanBuyCar(userId)">清空购物车</button></label>
                        <span class="fr">商品总价：<b style="font-size:22px; color:#ff4e00;">￥{{ cost }}</b></span>
                    </td>
                </tr>
                <tr valign="top" height="150">
                    <td colspan="6" align="right">
                        <a @click.prevent="toIndex()"><img src="/images/buy1.gif" /></a>&nbsp; &nbsp; <a @click.prevent="pay2()"><img src="/images/buy2.gif" /></a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
	<!--End 第一步：查看购物车 End--> 
  
    <FooterView></FooterView>
</template>

<script setup>
import { onMounted, ref, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import store from '@/store'
import HeaderSearch from '@/components/HeaderSearch.vue'
import HeaderMenu from '@/components/HeaderMenu.vue'
import FooterView from './FooterView.vue'

const router = useRouter()
const route = useRoute()

const userId = sessionStorage.getItem("id");
const cost = ref(0)
const conut = ref(0)
const numPatten = /^[1-9][0-9]*$/;
const productList = ref([])
const likeProList = ref({})
const isLike = ref(false)
const url = "http://192.168.12.159:83/"


//收藏夹
const addLike = async (productId) => {
    if(userId == null){
        return;
    }
    const response = await axios.post('/api/selectCollectProduct', {
        userId: userId,
    })
    likeProList.value = response.data.likeProductList

    if(likeProList.value==null){
        return;
    }
    
    for (let newProduct of likeProList.value) {
        if (newProduct.id == productId) {    
            alert("已收藏");
          isLike.value = true
        }
    }

    if(isLike.value==false){
        const response = await axios.post('/api/addCollectProduct', {
            userId: userId,
            productId: productId,
        })
        alert("收藏成功");
    }
    
}
//继续支付
const pay2 = () => {
    router.push('/buyCar_Two')
}

//首页
const toIndex = () => {
  router.push({name: 'index'})
}

//得到购物车的商品
const getProduct = async () => {
  if (userId == null) {
    return;
  }
  try {
    const request = await axios.get("/api/getProductForPayCar", {
      params: {
        userId: userId
      }
    })
    productList.value = request.data.productList;
    cost.value = 0;

    for (let i = 0; i < productList.value.length; i++) {
      cost.value += productList.value[i].price * productList.value[i].quantity;
      conut.value += productList.value[i].quantity;
    }


  } catch (error) {
    console.error('商品获取失败:', error)
  }

}


const updateQuantity = async (quantity,index,id) => { 
  console.log("quantity:",quantity);
  
  
  if(!numPatten.test(productList.value[index].quantity)){
        productList.value[index].quantity = 1;
        quantity = 1;
      alert("数量不能小于1");
    }

    if(productList.value[index].stock < quantity){
       productList.value[index].quantity = 1;
       quantity = 1;
          alert("库存不足")
    }

     console.log("changeQuantity:",quantity);
  
    updateProductCount(id, productList.value[index].stock,quantity);    
}

//修改商品数量
const updateProductCount = async (productId, stock, quantity) => {
  console.log("updateProductCount:",productId,stock,quantity);
  if(quantity>stock){
    alert("库存不足")
    
      return;
  }
  if(quantity<1){
    if (!confirm("是否移除该商品")) {
      return;
    }
  }

  try {
    const request = await axios.post('/api/payCar', {
      userId: userId,
      productId: productId,
      quantity: quantity,
    })
    console.log("updateProductCount");
    window.dispatchEvent(new CustomEvent('cart-updated'));

    getProduct();
  } catch (error) {
    console.error('收藏商品获取失败:', error)
  }
}

//删除购物车商品
const cleanBuyCar = async (userId) => {
  if (!confirm("是否清空购物车")) {
    return;
  }

    const request = await axios.get('/api/cleanBuyCar', {
      params: {
         userId: userId,
      },

     
    })


    if(request.data.code==5200){
      alert("清空成功")
    }
 window.dispatchEvent(new CustomEvent('cart-updated'));
    getProduct();
  
}

// 进入管理页面时隐藏HeaderView
onMounted(() => {
    getProduct()
    store.commit('setShowPage', 1)
})
// 离开管理页面时恢复HeaderView
onUnmounted(() => {
    store.commit('setShowPage', 0)
})
</script>

<style scoped>
</style>